package Singleton;
//懒汉模式：使用同步关键字进行延时创建
public class LazySingleton implements Runnable {
    private LazySingleton(){
        System.out.println("LazySingleton is create");
    }
    //创建单例
    private static LazySingleton instance = null;
    public static synchronized LazySingleton getInstance(){
        if (instance == null)
            instance = new LazySingleton();
        return instance;
    }
    //打印信息
    public static void createString(){
        System.out.println("create string");
    }
//由于引入了同步关键字，导致多线程环境下耗时明显增加
    public static void main(String[] args) {
//        LazySingleton.createString();
//        //只有在获取instance才会创建
//        LazySingleton.getInstance();
        for (int i = 0; i < 5; i++) {
           new Thread(new LazySingleton()).start();
        }
    }

    @Override
    public void run() {
        long beginTime = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            LazySingleton.getInstance();
        }
        System.out.println(System.currentTimeMillis()-beginTime);
    }
}
